import { BaseCoolQueue, CoolQueue } from '@cool-midway/task';
import { IMidwayApplication } from '@midwayjs/core';
import { App, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { UserRelationEntity } from '../../user/entity/user_relation';
import { FinanceProfitEntity } from '../../finance/entity/profit';
import { BaseSysParamEntity } from '../../base/entity/sys/param';
import { UserInfoService } from '../../user/service/info';
import { DeviceDeviceEntity } from '../../device/entity/device';

/**
 * 分润队列
 */
@CoolQueue()
export class OrderProfitQueue extends BaseCoolQueue {
  @App()
  app: IMidwayApplication;

  @InjectEntityModel(UserRelationEntity)
  userRelationEntity: Repository<UserRelationEntity>;

  @InjectEntityModel(FinanceProfitEntity)
  FinanceProfitEntity: Repository<FinanceProfitEntity>;

  @InjectEntityModel(BaseSysParamEntity)
  BaseSysParamEntity: Repository<BaseSysParamEntity>;

  @Inject()
  userInfoService: UserInfoService;

  /**
   * 处理分润计算
   * @param job 队列任务
   * @param done 完成回调
   */
  async data(job: any, done: any): Promise<void> {
    try {
      const { deviceInfo, orderNo, payAmount } = job.data;
      
      console.log(`开始处理分润计算 - 订单号: ${orderNo}, 金额: ${payAmount}`);
      
      await this.calculateProfit({ deviceInfo, orderNo, payAmount });
      
      console.log(`分润计算完成 - 订单号: ${orderNo}`);
      done();
    } catch (error) {
      console.error('分润计算失败:', error);
      // 抛出错误让队列重试，默认重试5次
      throw error;
    }
  }

  /**
   * 计算分润
   */
  private async calculateProfit({
    deviceInfo,
    orderNo,
    payAmount,
  }: {
    deviceInfo: DeviceDeviceEntity;
    orderNo: string;
    payAmount: number;
  }) {
    // 一级分佣金额
    let level1Profit = 0;
    // 二级分佣金额
    let level2Profit = 0;
    // 三级分佣金额
    let level3Profit = 0;
    /* 平台费率 */
    let platformProfitRate = 0;

    /* 读取平台费率 */
    const platformProfit = await this.BaseSysParamEntity.findOneBy({
      keyName: 'platform_fee_rate',
    });

    if (platformProfit?.data) {
      platformProfitRate = (platformProfit?.data * payAmount) / 100;
    }

    // 找到设备绑定用户的关系表
    const userRelation = await this.userRelationEntity.findOneBy({
      userId: deviceInfo.userId,
    });

    // 如果设备没有绑定用户，直接返回
    if (!userRelation) {
      console.log(`设备 ${deviceInfo.deviceNo} 未绑定用户，跳过分润计算`);
      return;
    }

    if (userRelation.level1ParentId) {
      const level1User = await this.userInfoService.person(
        userRelation.level1ParentId
      );
      // 记录一级分佣
      level1Profit = payAmount * (level1User.profitRatio / 100);
    }

    if (userRelation.level2ParentId) {
      const level2User = await this.userInfoService.person(
        userRelation.level2ParentId
      );
      // 记录二级分佣
      level2Profit = payAmount * (level2User.profitRatio / 100);
    }

    if (userRelation.level3ParentId) {
      const level3User = await this.userInfoService.person(
        userRelation.level3ParentId
      );
      // 记录三级分佣
      level3Profit = payAmount * (level3User.profitRatio / 100);
    }

    // 记录分佣
    await this.FinanceProfitEntity.save({
      orderId: orderNo,
      level1Amount: level1Profit,
      level2Amount: level2Profit,
      level3Amount: level3Profit,
      profitTime: new Date(),
      totalAmount: payAmount,
      platformRatio: platformProfitRate,
      sellerAmount:
        payAmount -
        platformProfitRate -
        level1Profit -
        level2Profit -
        level3Profit,
    });

    console.log(`分润记录保存成功 - 订单号: ${orderNo}, 一级: ${level1Profit}, 二级: ${level2Profit}, 三级: ${level3Profit}`);
  }
}